// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_member_api_serv

import (
	"context"
	"time"

	"gitcode.com/lvupclub/lvup-api/dao"
	"gitcode.com/lvupclub/lvup-api/dao/roadmap_dao"
	"gitcode.com/lvupclub/lvup-api/dao/user_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_member_api"
)

func (apiImpl *RoadmapMemberApiImpl) Join(ctx context.Context, req *roadmap_member_api.JoinRequest) (*roadmap_member_api.JoinResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_member_api.JoinResponse{
			Code:   roadmap_member_api.JoinResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	inviteItem, err := roadmap_dao.InviteInfoDao.Get(ctx, req.InviteCode)
	if err != nil {
		return &roadmap_member_api.JoinResponse{
			Code:   roadmap_member_api.JoinResponse_CODE_NO_INVITE,
			ErrMsg: "邀请不存在",
		}, nil
	}
	nowTime := time.Now().UnixMilli()
	if inviteItem.ExpireTime < nowTime {
		return &roadmap_member_api.JoinResponse{
			Code:   roadmap_member_api.JoinResponse_CODE_NO_INVITE,
			ErrMsg: "邀请不存在",
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, inviteItem.RoadmapId)
	if err != nil {
		return &roadmap_member_api.JoinResponse{
			Code:   roadmap_member_api.JoinResponse_CODE_NO_INVITE,
			ErrMsg: "邀请不存在",
		}, nil
	}
	if roadmapItem.OwnerUserId == sessItem.UserId { //路线图owner不用成为成员
		return &roadmap_member_api.JoinResponse{
			Code: roadmap_member_api.JoinResponse_CODE_OK,
		}, nil
	}

	exist, err := roadmap_dao.RoadmapMemberDao.Exist(ctx, inviteItem.RoadmapId, sessItem.UserId)
	if err != nil {
		return nil, err
	}
	if exist {
		return &roadmap_member_api.JoinResponse{
			Code: roadmap_member_api.JoinResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		planCount, err := roadmap_dao.PlanInfoDao.Count(sessCtx, inviteItem.RoadmapId, sessItem.UserId)
		if err != nil {
			return nil, err
		}
		err = roadmap_dao.RoadmapMemberDao.Insert(sessCtx, &roadmap_dao.MemberInfoDbItem{
			RoadmapId:    inviteItem.RoadmapId,
			MemberUserId: sessItem.UserId,
			JoinTime:     nowTime,
			PlanCount:    planCount,
		})
		if err != nil {
			return nil, err
		}
		return &roadmap_member_api.JoinResponse{
			Code: roadmap_member_api.JoinResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_member_api.JoinResponse), nil
}

func (apiImpl *RoadmapMemberApiImpl) Leave(ctx context.Context, req *roadmap_member_api.LeaveRequest) (*roadmap_member_api.LeaveResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_member_api.LeaveResponse{
			Code:   roadmap_member_api.LeaveResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	exist, err := roadmap_dao.RoadmapMemberDao.Exist(ctx, req.RoadmapId, sessItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_member_api.LeaveResponse{
			Code: roadmap_member_api.LeaveResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = apiImpl.processRemoveMember(sessCtx, req.RoadmapId, sessItem.UserId)
		if err != nil {
			return nil, err
		}
		return &roadmap_member_api.LeaveResponse{
			Code: roadmap_member_api.LeaveResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_member_api.LeaveResponse), nil
}

func (apiImpl *RoadmapMemberApiImpl) processRemoveMember(ctx context.Context, roadmapId, memberUserId string) error {
	//删除成员
	return roadmap_dao.RoadmapMemberDao.Remove(ctx, roadmapId, memberUserId)
}

func (apiImpl *RoadmapMemberApiImpl) RemoveMember(ctx context.Context, req *roadmap_member_api.RemoveMemberRequest) (*roadmap_member_api.RemoveMemberResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_member_api.RemoveMemberResponse{
			Code:   roadmap_member_api.RemoveMemberResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_member_api.RemoveMemberResponse{
			Code:   roadmap_member_api.RemoveMemberResponse_CODE_NO_ROADMAP,
			ErrMsg: "成长路线图不存在",
		}, nil
	}
	if roadmapItem.OwnerUserId != sessItem.UserId {
		return &roadmap_member_api.RemoveMemberResponse{
			Code:   roadmap_member_api.RemoveMemberResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	exist, err := roadmap_dao.RoadmapMemberDao.Exist(ctx, req.RoadmapId, req.TargetMemberUserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_member_api.RemoveMemberResponse{
			Code: roadmap_member_api.RemoveMemberResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = apiImpl.processRemoveMember(sessCtx, req.RoadmapId, req.TargetMemberUserId)
		if err != nil {
			return nil, err
		}
		return &roadmap_member_api.RemoveMemberResponse{
			Code: roadmap_member_api.RemoveMemberResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_member_api.RemoveMemberResponse), nil
}

func (apiImpl *RoadmapMemberApiImpl) ListMember(ctx context.Context, req *roadmap_member_api.ListMemberRequest) (*roadmap_member_api.ListMemberResponse, error) {
	emptyList := []*roadmap_member_api.MemberInfo{}

	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_member_api.ListMemberResponse{
			Code:       roadmap_member_api.ListMemberResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			MemberList: emptyList,
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_member_api.ListMemberResponse{
			Code:       roadmap_member_api.ListMemberResponse_CODE_NO_ROADMAP,
			ErrMsg:     "成长路线图不存在",
			MemberList: emptyList,
		}, nil
	}
	if roadmapItem.OwnerUserId != sessItem.UserId {
		return &roadmap_member_api.ListMemberResponse{
			Code:       roadmap_member_api.ListMemberResponse_CODE_NO_PERMISSION,
			ErrMsg:     "没有权限",
			MemberList: emptyList,
		}, nil
	}

	count, err := roadmap_dao.RoadmapMemberDao.CountByRoadmap(ctx, req.RoadmapId)
	if err != nil {
		return nil, err
	}
	memberItemList, err := roadmap_dao.RoadmapMemberDao.ListByRoadmap(ctx, req.RoadmapId, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//补全用户信息
	userIdList := []string{}
	for _, memberItem := range memberItemList {
		userIdList = append(userIdList, memberItem.MemberUserId)
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//生成结果
	memberList := []*roadmap_member_api.MemberInfo{}
	for _, memberItem := range memberItemList {
		member := memberItem.ToMemberInfo()
		userItem, ok := userItemMap[memberItem.MemberUserId]
		if ok {
			member.MemberDisplayName = userItem.BasicInfo.DisplayName
			member.MemberLogouri = userItem.BasicInfo.LogoUri
		}
		memberList = append(memberList, member)
	}
	return &roadmap_member_api.ListMemberResponse{
		Code:       roadmap_member_api.ListMemberResponse_CODE_OK,
		TotalCount: count,
		MemberList: memberList,
	}, nil
}

func (apiImpl *RoadmapMemberApiImpl) GetMember(ctx context.Context, req *roadmap_member_api.GetMemberRequest) (*roadmap_member_api.GetMemberResponse, error) {
	emptyInfo := &roadmap_member_api.MemberInfo{}

	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_member_api.GetMemberResponse{
			Code:   roadmap_member_api.GetMemberResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
			Member: emptyInfo,
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_member_api.GetMemberResponse{
			Code:   roadmap_member_api.GetMemberResponse_CODE_NO_ROADMAP,
			ErrMsg: "成长路线图不存在",
			Member: emptyInfo,
		}, nil
	}
	if roadmapItem.OwnerUserId != sessItem.UserId {
		return &roadmap_member_api.GetMemberResponse{
			Code:   roadmap_member_api.GetMemberResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
			Member: emptyInfo,
		}, nil
	}

	memberItem, err := roadmap_dao.RoadmapMemberDao.Get(ctx, req.RoadmapId, req.TargetMemberUserId)
	if err != nil {
		return &roadmap_member_api.GetMemberResponse{
			Code:   roadmap_member_api.GetMemberResponse_CODE_NO_TARGET_MEMBER,
			ErrMsg: "目标成员不存在",
			Member: emptyInfo,
		}, nil
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, []string{req.TargetMemberUserId})
	if err != nil {
		return nil, err
	}

	member := memberItem.ToMemberInfo()
	if len(userItemList) > 0 {
		member.MemberDisplayName = userItemList[0].BasicInfo.DisplayName
		member.MemberLogouri = userItemList[0].BasicInfo.LogoUri
	}
	return &roadmap_member_api.GetMemberResponse{
		Code:   roadmap_member_api.GetMemberResponse_CODE_OK,
		Member: member,
	}, nil
}
